import { Component } from '@angular/core';
import { ApesField } from '@shared/ui-zorro/src/types/apes-field';
import { ApiService } from '@core/services/http/api.service';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';
import { exists, getO } from '../../../../utils/utils';

@Component({
  selector: 'formly-field-statistic',
  template: `
    <div class="apes-statistic" [ngStyle]="bodyStyle">
      <div class="apes-statistic-title" [ngStyle]="titleStyle">
        {{title}}
        <span *ngIf="getTooltip()"><i apes-icon apesType="info-circle" apes-tooltip
                                      [apesTooltipTitle]="tooltipTemplate"
                                      class="apes-statistic-tooltip"></i></span>
        <ng-template #tooltipTemplate>
          <span [innerHTML]="showTooltip()"></span>
        </ng-template>
      </div>
      <div class="apes-statistic-value" [ngStyle]="valueStyle">{{Value}}</div>
    </div>
  `,
  styles: [`
    .apes-statistic {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      border: 1px solid #eeeeee;
      border-radius: 4px;
      background: #fafafa;
      margin: 8px 8px 16px;
      padding: 16px;
    }
    .apes-statistic-title {
      font-size: 18px;
      font-weight: bold;
    }

    .apes-statistic-tooltip {
      cursor: pointer;
      position: relative;
      top: 2px;
      color: #e6a23c;
    }

    .apes-statistic-value {
      font-size: 16px;
    }
  `],
})
export class FormlyFieldStatistic extends ApesField {

  title: any;
  bodyStyle: any;
  titleStyle : any;
  valueStyle : any;

  constructor(
    protected apiService: ApiService,
    protected events: Events,
    protected expressionService: ExpressionService,
    protected subject: SubjectService) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit() {
    this.title = this.to.title;
    this.bodyStyle = getO(this.to.bodyStyle);
    this.titleStyle = getO(this.to.titleStyle);
    this.valueStyle = getO(this.to.valueStyle);
  }

  getTooltip() {
    return !!this.to.tooltipFormatter;
  }

  showTooltip() {
    let value = this.model[this.key];
    let expression = this.to.tooltipFormatter || 'value';
    let tooltip = this.expressionService.evaluate(expression, {
      context: this.formState,
      model: this.model,
      value: value,
    }, true);
    if (tooltip == null) {
      tooltip = this.to.tooltipFormatter;
    }
    return tooltip;
  }

  get Value() {
    return this.formControl.value || '0';
  }
}
